package com.omuao.cloud.stabilization.common.message.core.impl;

import com.omuao.cloud.stabilization.common.message.core.MessageProducer;
import com.omuao.cloud.stabilization.common.message.core.config.MessageQueueProcessor;
import com.omuao.cloud.stabilization.common.message.core.metadata.MessageQueueData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.binding.BinderAwareChannelResolver;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Collections;


/**
 * 标准消息生产者实现
 *
 * @author yumi
 */
@Component
public class StandardMessageProducerImpl implements MessageProducer {

    public static final String SPLITTER = MessageQueueProcessor.SPLITTER;

    /**
     * 动态消息发布
     */
    @Autowired
    private BinderAwareChannelResolver resolver;

    @Override
    public boolean send(String topic, String tag, String contentType, Object message) {
        return resolver.resolveDestination(topic.concat(SPLITTER).concat(tag)).send(MessageBuilder.createMessage(message,
                new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, contentType))));
    }

    @Override
    public boolean send(MessageQueueData queueData) {
        if (queueData.getTimeout() == null) {
            return send(queueData.getTopic(), queueData.getTag(), queueData.getContentType(), queueData.getBody());
        }
        return resolver.resolveDestination(queueData.getTopic().concat(SPLITTER).concat(queueData.getTag())).send(MessageBuilder.createMessage(queueData.getBody(),
                new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, queueData.getContentType()))), queueData.getTimeout());
    }
}
